﻿/**
 * @author alex
 */
Namespace("sketch.framework.text");

(function () {
    var txt = sketch.framework.text;
    txt.TextMeasure = {};
    txt.TextMeasure.updateTokens = function(tokenLines, width, textAlign, measureCallback) {
        var currentLine = 0;
        var currentWidth = 0;
        var lines = [];
        var lastWidth,
            lastMinWidth;
        for (var i = 0, length = tokenLines.length; i < length; i++) {
            var tokens = tokenLines[i];
            for (var j = 0, tl = tokens.length; j < tl; j++) {
                var token = tokens[j];

                var measure = measureCallback(token);
                var tw = measure.width;
                if ((currentWidth + measure.minWidth) > width && currentWidth !== 0) { // exceeded box width
                    if (textAlign == 'center') {
                        lines[currentLine] = {offset: ~~(width - currentWidth - lastWidth + lastMinWidth) / 2};
                    }
                    else if (textAlign == 'left') {
                        lines[currentLine] = {offset:0};
                    }
                    else if (textAlign == 'right') {
                        lines[currentLine] = {offset: ~~(width - currentWidth - lastWidth + lastMinWidth)};
                    }
                    currentWidth = 0;
                    currentLine++;
                }

                //TODO: use minWidth

                token.x = currentWidth;
                token.line = currentLine;
                lastWidth = measure.width;
                lastMinWidth = measure.minWidth;
                currentWidth += tw;
            }
            if (textAlign == 'center') {
                lines[currentLine] = {offset: ~~(width - currentWidth - lastWidth + lastMinWidth) / 2};
            }
            else if (textAlign == 'left') {
                lines[currentLine] = {offset:0};
            }else if (textAlign == 'right') {
                lines[currentLine] = {offset: ~~(width - currentWidth - lastWidth + lastMinWidth)};
            }
            currentWidth = 0;
            currentLine++;
        }

        return lines;
    }
})();